﻿using MFTool;
using MF_Base;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
using MF_Base.Model;
using UIBase;
using UIBase.Helper;

namespace AutoUI.Areas.Sys.Controllers
{
    [Export]
    public class FuncManageController : BaseController
    {
        public ActionResult List()
        {
            //ViewBag.RoleFunc = RoleFunc;
            return View();
        }

        public ActionResult Item()
        {
            return View();
        }

        public ActionResult RoleFunc()
        {
            return View();
        }

        public JsonResult GetFuncTreeJson()
        {
            var res = UnitOfWork.Get<MF_Func>();
            return Json(EasyUIHelper.GetTreeJson(res));
        }

        public JsonResult GetFunc(string id)
        {
            id.CheckNotNullOrEmpty("id");
            var func = UnitOfWork.GetByKey<MF_Func>(id);
            return Json(func);
        }

        public JsonResult AddEqFunc(string data)
        {
            MF_Func func = data.JsonToObject<MF_Func>();
            MF_Func funcToAdd = new MF_Func();
            funcToAdd.Id = GuidHelper.CreateTimeOrderID();
            funcToAdd.Text = "新增项";
            funcToAdd.ParentId = func.ParentId;
            funcToAdd.FullId = func.FullId.Replace(func.Id, funcToAdd.Id);
            if (func.EnumFuncType == EnumFuncType.Module.ToString())
            {
                funcToAdd.EnumFuncType = EnumFuncType.Module.ToString();
            }
            else if (func.EnumFuncType == EnumFuncType.Menu.ToString())
            {
                funcToAdd.EnumFuncType = EnumFuncType.Menu.ToString();
            }
            //else if (func.EnumFuncType == EnumFuncType.Page.ToString())
            //{
            //    funcToAdd.EnumFuncType = EnumFuncType.Page.ToString();
            //}
            //else if (func.EnumFuncType == EnumFuncType.Button.ToString())
            //{
            //    funcToAdd.EnumFuncType = EnumFuncType.Button.ToString();
            //}

            var res = UnitOfWork.Add(funcToAdd);
            UnitOfWork.Commit();
            return Json(res);
        }

        public JsonResult AddSubFunc(string data)
        {
            MF_Func func = data.JsonToObject<MF_Func>();
            MF_Func funcToAdd = new MF_Func();
            funcToAdd.Id = GuidHelper.CreateTimeOrderID();
            funcToAdd.Text = "新增项";
            funcToAdd.ParentId = func.Id;
            funcToAdd.FullId = func.FullId + "." + funcToAdd.Id;
            if (func.EnumFuncType == EnumFuncType.Module.ToString())
            {
                funcToAdd.EnumFuncType = EnumFuncType.Menu.ToString();
            }
            else if (func.EnumFuncType == EnumFuncType.Menu.ToString())
            {
                funcToAdd.EnumFuncType = EnumFuncType.Menu.ToString();
            }
            //else if (func.EnumFuncType == EnumFuncType.Menu.ToString())
            //{
            //    funcToAdd.EnumFuncType = EnumFuncType.Page.ToString();
            //}
            //else if (func.EnumFuncType == EnumFuncType.Page.ToString())
            //{
            //    funcToAdd.EnumFuncType = EnumFuncType.Button.ToString();
            //}

            var res = UnitOfWork.Add(funcToAdd);
            UnitOfWork.Commit();
            return Json(res);
        }

        public JsonResult ExChangeOrder(string aId, string bId)
        {
            var a = UnitOfWork.GetByKey<MF_Func>(aId);
            var b = UnitOfWork.GetByKey<MF_Func>(bId);
            var orderIndex = a.OrderIndex;
            a.OrderIndex = b.OrderIndex;
            b.OrderIndex = orderIndex;

            return Json(UnitOfWork.Commit());
        }

        public JsonResult DeleteFunc(string id)
        {
            var allChildren = GetAllChildren(id);
            foreach (var child in allChildren)
            {
                UnitOfWork.Delete<MF_FuncRole>(a => a.MF_FuncId == child.Id);
            }
            UnitOfWork.Delete<MF_FuncRole>(a => a.MF_FuncId == id);
            UnitOfWork.Delete<MF_Func>(GetAllChildren(id));
            UnitOfWork.DeleteByKey<MF_Func>(id);
            return Json(UnitOfWork.Commit());
        }

        public JsonResult Save()
        {
            var dic = Request.Form["formData"].JsonToObject<Dictionary<string, object>>();
            MF_Func cForm = ConvertHelper.ConvertToObj<MF_Func>(dic);

            if (string.IsNullOrEmpty(cForm.Id))
            {
                cForm.Id = GuidHelper.CreateTimeOrderID();
                UnitOfWork.Add(cForm);
            }
            else
            {
                UnitOfWork.UpdateEntity(cForm);
            }

            return Json(UnitOfWork.Commit());
        }

        #region 角色权限
        public JsonResult GetRoleList()
        {
            string roleType = QueryString("RoleType");
            roleType.CheckNotNullOrEmpty("角色枚举类型不能为空");

            int totalCount = 0;
            int pageId = Convert.ToInt32(QueryString("page"));
            int pageSize = Convert.ToInt32(QueryString("rows"));
            IEnumerable<MF_Role> baseForms = UnitOfWork.GetByPage<MF_Role, string>
                (out totalCount, pageSize, pageId, a => a.Id, false, a => a.EnumRoleType == EnumRoleType.Sys.ToString());
            return Json(new { rows = baseForms, total = totalCount });
        }

        public JsonResult GetFuncList(string roleId)
        {
            var res = UnitOfWork.Get<MF_Func>().GroupJoin(UnitOfWork.GetQuery<MF_FuncRole>().Where(a => a.MF_RoleId == roleId), a => a.Id, b => b.MF_FuncId,
                (a, b) => new { a.Id, a.ParentId, a.FullId, a.OrderIndex, a.Text, Set = b.Count() != 0 ? "true" : "false" });

            return Json(EasyUIHelper.GetTreeJson(res));
        }

        public JsonResult UpdateRoleFunc(string roleId, string row)
        {
            var rowDic = row.JsonToDictionary();
            string funcId = rowDic.GetValue("Id");
            string funcFullId = rowDic.GetValue("FullId");
            if (rowDic.GetValue("Set") == "true")
            {
                //所有子项
                List<MF_Func> funcList = UnitOfWork.Get<MF_Func>(a => a.FullId.Contains(funcId)).ToList();
                foreach (var func in funcList)
                {
                    if (!UnitOfWork.IsExist<MF_FuncRole>(a => a.MF_FuncId == func.Id && a.MF_RoleId == roleId))
                    {
                        UnitOfWork.Add<MF_FuncRole>(new MF_FuncRole() {
                            Id = GuidHelper.CreateTimeOrderID(),
                            MF_RoleId = roleId,
                            MF_FuncId = func.Id
                        });
                    }                    
                }

                //父项                
                List<MF_Func> allParents = UnitOfWork.GetQuery<MF_Func>().Where(a => funcFullId.Contains(a.Id) && a.Id != funcId).ToList();
                foreach (var func in allParents)
                {
                    if (!UnitOfWork.IsExist<MF_FuncRole>(a => a.MF_FuncId == func.Id && a.MF_RoleId == roleId))
                    {
                        UnitOfWork.Add<MF_FuncRole>(new MF_FuncRole()
                        {
                            Id = GuidHelper.CreateTimeOrderID(),
                            MF_RoleId = roleId,
                            MF_FuncId = func.Id
                        });
                    }
                }

                UnitOfWork.Add<MF_FuncRole>(new MF_FuncRole() { Id = GuidHelper.CreateTimeOrderID(), MF_RoleId = roleId, MF_FuncId = funcId });
            }
            else
            {
                UnitOfWork.Delete<MF_FuncRole>(a => a.MF_RoleId == roleId && a.MF_Func.FullId.Contains(funcId));
            }

            return Json(UnitOfWork.Commit());
        }
        #endregion

        private List<MF_Func> GetAllChildren(string funcId)
        {
            List<MF_Func> temps = new List<MF_Func>();
            var children = UnitOfWork.Get<MF_Func>(a => a.ParentId == funcId);
            foreach (var child in children)
            {
                temps.Add(child);
                temps.AddRange(GetAllChildren(child.Id));
            }
            return temps;
        }
    }
}
